﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using Module;

namespace HospitalManager.QuanTriHeThong.DanhMuc
{
    public partial class DMBuong : System.Web.UI.Page
    {
        private Module.QuanTriHeThong.DanhMuc.DMBuong _dmBuong = new Module.QuanTriHeThong.DanhMuc.DMBuong();
        private readonly SelectAllClass _selectAllClass = new SelectAllClass();
        private int _totalrow;
        private const int PageSize = 20;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            if (Session["username"] == null)
            {
                Response.RedirectToRoute("DangNhap");
            }
            LoadKhoa();
            LoadPage();
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ViewState["CheckRefresh"] = Session["CheckRefresh"];
        }

        private void LoadKhoa()
        {
            ddlKhoa.DataSource = _selectAllClass.SelectAllKhoa();
            ddlKhoa.DataTextField = "TenKhoa";
            ddlKhoa.DataValueField = "MaKhoa";
            ddlKhoa.DataBind();
            ddlKhoa.Items.Insert(0, new ListItem("Chọn", ""));
        }

        private void LoadPage()
        {
            _dmBuong = new Module.QuanTriHeThong.DanhMuc.DMBuong();
            if (hfTimKiem.Value.Equals("true"))
            {
                _dmBuong.MaBuong = txtMaBuong.Text.Trim();
                _dmBuong.TenBuong = txtTenBuong.Text.Trim();
                _dmBuong.MaKhoa = ddlKhoa.SelectedValue.Trim();
            }
            gvDanhMuc.DataSource = _dmBuong.SelectAll(_dmBuong, Convert.ToInt32(hfPageIndex.Value.Trim()), PageSize,
                out _totalrow);
            gvDanhMuc.DataBind();
            GeneratePager(_totalrow, PageSize, Convert.ToInt32(hfPageIndex.Value.Trim()));
            Session["CheckRefresh"] = Server.UrlEncode(DateTime.Now.ToString(CultureInfo.InvariantCulture));
        }

        private void ResetPage()
        {
            txtMaBuong.Text = string.Empty;
            txtMaBuong.Enabled = true;
            txtTenBuong.Text = string.Empty;
            ddlKhoa.SelectedValue = "";
            hfTimKiem.Value = "false";
            hfStatus.Value = "false";
            hfPageIndex.Value = "1";
            LoadPage();
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
            {
                Response.RedirectToRoute("DangNhap");
            }
            else
            {
                if (Session["CheckRefresh"].ToString() != ViewState["CheckRefresh"].ToString())
                {
                    ResetPage();
                }
                else
                {
                    _dmBuong.MaBuong = txtMaBuong.Text.Trim();
                    _dmBuong.TenBuong = txtTenBuong.Text.Trim();
                    _dmBuong.MaKhoa = ddlKhoa.SelectedValue.Trim();
                    if (hfStatus.Value.Equals("false"))
                    {
                        var CheckMa = _dmBuong.SelectById(_dmBuong.MaBuong).Rows.Count > 0;
                        if (!CheckMa)
                        {
                            _dmBuong.Insert(_dmBuong);
                        }
                        else
                        {
                            ClientScript.RegisterClientScriptBlock(typeof(string), "alert", "bootbox.alert('Mã nhóm vật tư đã tồn tại, vui lòng nhập mã khác!')", true);
                        }
                    }
                    else
                    {
                        _dmBuong.Update(_dmBuong);
                    }
                    ResetPage();
                }
            }
        }

        protected void btnXoa_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
            {
                Response.RedirectToRoute("DangNhap");
            }
            else
            {
                if (Session["CheckRefresh"].ToString() != ViewState["CheckRefresh"].ToString())
                {
                    ResetPage();
                }
                else
                {
                    foreach (GridViewRow gvrow in gvDanhMuc.Rows)
                    {
                        var checkId = (CheckBox)gvrow.FindControl("check_id");
                        if (!checkId.Checked) continue;
                        var dataKey = gvDanhMuc.DataKeys[gvrow.RowIndex];
                        if (dataKey == null) continue;
                        if (dataKey.Values == null) continue;
                        var id = dataKey.Values["MaBuong"].ToString();
                        _dmBuong.Delete(id);
                    }
                    ResetPage();
                }
            }
        }

        protected void btnTimKiem_Click(object sender, EventArgs e)
        {
            txtMaBuong.Enabled = true;
            hfTimKiem.Value = "true";
            hfPageIndex.Value = "1";
            LoadPage();
        }

        protected void btnNhaplai_Click(object sender, EventArgs e)
        {
            ResetPage();
        }

        protected void dlPager_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName != "PageNo") return;
            hfPageIndex.Value = e.CommandArgument.ToString();
            LoadPage();
            e.Item.Attributes.Add("disabled", "disabled");
        }

        public void GeneratePager(int totalRowCount, int pageSize, int currentPage)
        {
            const int totalLinkInPage = 4;
            var totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);

            var startPageLink = Math.Max(currentPage - (int)Math.Floor((decimal)totalLinkInPage / 2), 1);
            var lastPageLink = Math.Min(startPageLink + totalLinkInPage - 1, totalPageCount);

            if ((startPageLink + totalLinkInPage - 1) > totalPageCount)
            {
                lastPageLink = Math.Min(currentPage + (int)Math.Floor((decimal)totalLinkInPage / 2), totalPageCount);
                startPageLink = Math.Max(lastPageLink - totalLinkInPage + 1, 1);
            }

            var pageLinkContainer = new List<ListItem>();

            if (startPageLink != 1)
            {
                pageLinkContainer.Add(new ListItem("«", "1", currentPage != 1));
            }
            for (var i = startPageLink; i <= lastPageLink; i++)
            {
                pageLinkContainer.Add(new ListItem(i.ToString(CultureInfo.InvariantCulture),
                    i.ToString(CultureInfo.InvariantCulture), currentPage != i));
            }
            if (lastPageLink != totalPageCount)
                pageLinkContainer.Add(new ListItem("»", totalPageCount.ToString(CultureInfo.InvariantCulture),
                    currentPage != totalPageCount));

            dlPager.DataSource = pageLinkContainer;
            dlPager.DataBind();
        }

        protected void gvDanhMuc_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.DataRow ||
                   (e.Row.RowState != DataControlRowState.Normal && e.Row.RowState != DataControlRowState.Alternate))
                return;
            var checkId = (CheckBox)e.Row.Cells[1].FindControl("check_id");
            var checkallId = (CheckBox)gvDanhMuc.HeaderRow.FindControl("checkall_id");
            checkId.Attributes["onclick"] = string.Format
                (
                    "javascript:checkClick(this,'{0}');",
                    checkallId.ClientID
                );
        }

        protected void btnSua_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
            {
                Response.RedirectToRoute("DangNhap");
            }
            else
            {
                if (Session["CheckRefresh"].ToString() != ViewState["CheckRefresh"].ToString())
                {
                    ResetPage();
                }
                else
                {
                    hfStatus.Value = "true";
                    txtMaBuong.Text = ((LinkButton)sender).CommandArgument;
                    txtMaBuong.Enabled = false;
                    var dt = _dmBuong.SelectById(txtMaBuong.Text.Trim());
                    if (dt.Rows.Count <= 0) return;
                    txtTenBuong.Text = dt.Rows[0]["TenBuong"].ToString().Trim();
                    txtTenBuong.Focus();
                    ddlKhoa.SelectedValue = dt.Rows[0]["MaKhoa"].ToString().Trim();
                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
            {
                Response.RedirectToRoute("DangNhap");
            }
            else
            {
                if (Session["CheckRefresh"].ToString() != ViewState["CheckRefresh"].ToString())
                {
                    ResetPage();
                }
                else
                {
                    var str = _dmBuong.Delete((((LinkButton)sender).CommandArgument).Trim())
                        ? "bootbox.alert('Xóa thành công!')"
                        : "bootbox.alert('Xóa thất bại!')";
                    ClientScript.RegisterClientScriptBlock(typeof(string), "alert", str, true);
                    ResetPage();
                }
            }
        }
    }
}